package com.vcs.frm.dao.common;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.vcs.frm.domain.Job;
import com.vcs.frm.domain.User;

@Repository
public class CommonDaoImpl implements CommonDao {

	/* Logger object */
	private final Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private SessionFactory sessionFactory;
	private HibernateTemplate hibernateTemplate;

	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	/**
	 * returns a User instance by username
	 * @see com.vcs.frm.dao.common.CommonDao#getUserByUsername(java.lang.String)
	 */
	@Override
	public User getUserByUsername(String username) {

		Session session = sessionFactory.getCurrentSession();

		User user = (User) session.createQuery(
				"from User as u where u.username like :uname").setString(
				"uname", username).uniqueResult();

		return user;
	}

	@Override
	public List<Job> getRecentJobs(int size) {
		Session session = sessionFactory.getCurrentSession();
		
		String hql = "from  Job j order by j.createdDate desc";
		
		Query query = session.createQuery(hql); 
		query.setMaxResults(size);
		
		List<Job> recentJobs = (List<Job>) query.list();
		log.info("recent jobs : "+recentJobs.size());
		
		return recentJobs;
	}

	@Override
	public Job getJobByJobId(Long jobId) {
		
		Session session = sessionFactory.getCurrentSession();
		
		Job job = (Job)session.get(Job.class, jobId);
		return job;
	}

	@Override
	public Long saveUser(User user) {
		Session session = sessionFactory.getCurrentSession();
		Long userId = (Long) session.save(user);
		return userId;
	}

	@Override
	public void updateUser(User user) {
		Session session = sessionFactory.getCurrentSession();
		session.update(user);
	}

	@Override
	public User getUserById(Long userId) {
		Session session = sessionFactory.getCurrentSession();
		User user = (User) session.get(User.class, userId);
		return user;
	}
	
}
